
package com.jf.cloud.search.listener;

import cn.throwx.canal.gule.model.CanalBinLogResult;
import com.jf.cloud.api.order.bo.EsOrderRefundBO;
import com.jf.cloud.api.order.feign.OrderRefundFeignClient;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.search.bo.OrderRefundBO;
import com.jf.cloud.search.constant.EsIndexEnum;
import com.jf.cloud.search.util.EsSearchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author zz
 * @date 2022/8/23
 */
@Component
public class OrderRefundCanalListener extends BaseCanalBinlogEventThrowExceptionProcessor<OrderRefundBO> {

    private static final Logger log = LoggerFactory.getLogger(OrderRefundCanalListener.class);

    @Autowired
    private OrderRefundFeignClient orderRefundFeignClient;

    /**
     * 插入商品，此时插入es
     */
    @Override
    protected void processInsertInternal(CanalBinLogResult<OrderRefundBO> result) {
        Long refundId = result.getPrimaryKey();
        EsOrderRefundBO orderRefund = getEsOrderRefundData(refundId);
        if (Objects.isNull(orderRefund)) {
            log.error("订单信息异常的订单id为：{}", refundId);
            return;
        }
        EsSearchUtil.esSave(orderRefund.getRefundId(),EsIndexEnum.ORDER_REFUND, orderRefund);
    }

    /**
     * 更新订单数据
     */
    @Override
    protected void processUpdateInternal(CanalBinLogResult<OrderRefundBO> result) {
        OrderRefundBO afterData = result.getAfterData();
        EsOrderRefundBO orderRefund = getEsOrderRefundData(afterData.getRefundId());
        if (Objects.isNull(orderRefund)) {
            log.error("订单信息异常的订单id为：{}", afterData.getRefundId());
            return;
        }
        EsSearchUtil.esUpdate(orderRefund.getRefundId(),EsIndexEnum.ORDER_REFUND, orderRefund);
    }

    private EsOrderRefundBO getEsOrderRefundData(Long refundId) {
        ServerResponseEntity<EsOrderRefundBO> orderResponseEntity = orderRefundFeignClient.saveMongoAndGetEsOrderRefundInfo(refundId);
        if (orderResponseEntity.isFail()) {
            throw new LuckException(orderResponseEntity.getMsg());
        }
        // 添加es中保存的订单数据
        return orderResponseEntity.getData();
    }
}
